<!-- 表格多选 -->

<template>
  <FormSlot :bind="`no_${obj.no}`" tip="请选择每一行" noLabel :required="obj.required === 1">
    <div class="QuestionnaireDetail-MyQuestion-table">
      <div class="flex">
        <div class="flex2" />
        <div v-for="option in obj.optionList" :key="option.key" class="flex1">{{ option.content }}</div>
      </div>

      <FormSlot
        v-for="question in obj.questionList"
        :key="question.key"
        :bind="`no_${obj.no}_${question.no}`"
        noLabel
        :required="obj.required === 1"
      >
        <div class="flex">
          <div class="flex2">{{ question.title }}</div>
          <div v-for="option in obj.optionList" :key="option.key" class="flex1">
            <el-checkbox v-bind="getProps(question, option)" @change="toChange(question, option)" />
          </div>
        </div>
      </FormSlot>
    </div>
  </FormSlot>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import MyRadio from '../MyRadio'

// ============================== 导出组件 ============================== //

export default CORE.extend(MyRadio, {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MyCheckboxTable',

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 校验
     */
    check(value) {
      const arr = value ? value.split(' ') : []
      const { min, max } = this.obj

      if (min && arr.length < min) return `最少 ${min}项`
      if (max && max.length > max) return `最多 ${max}项`
      return ''
    },

    /**
     * 获取属性
     */
    getProps(question, option) {
      const { obj: { no }, form, disabled } = this
      const value = form[`no_${no}_${question.no}`].includes(option.label)
      return { value, label: option.label, disabled }
    },

    /**
     * 数据改变
     */
    toChange(question, option) {
      const { obj: { no, questionList }, form } = this

      if (question && option) {
        const { value, label } = this.getProps(question, option)
        const key = `no_${no}_${question.no}`
        let arr = form[key] ? form[key].split(' ') : []

        if (value) arr = arr.filter(item => item !== label)
        else arr.push(label)

        arr.sort()
        form[key] = arr.join(' ')
      }

      const valueList = questionList.map((sub) => form[`no_${no}_${sub.no}`] || '')
      form[`no_${no}`] = valueList.every((value) => value) ? 'ready' : ''
    },
  },
})
</script>
